/*
 * Created on 2006-04-30
 *
 * Copyright: Bluejay Networks Inc. & Inquiry Management Systems Ltd.  2004
 *
 * This software is the proprietary information of Bluejay Networks Inc. & 
 * Inquiry Management Systems Ltd.  
 * Use is subject to license terms.
 */
package com.ims.iaa.JavaScript;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.JavaScriptException;

import com.ims.iaa.IaaUtil;
import com.ims.iaa.URLUtil;
import com.ims.iaa.html.ImpAnalyzer;
import com.ims.iaa.html.ImpAnalyzerImpl;
import com.ims.iaa.html.TagAttributeParser;

/**
 * @author changsheng
 * TODO catch the chechM8 javascript ad
 */
public class CheckM8JSParser extends JavaScriptParser{
	
    protected static final String CM8_SRC = "http://web.checkM8.com/adam/cm8adam_1_call.js" ;
  
	/**
	 * @param baseUrl
	 * @param impa
	 * @param out
	 */
	public CheckM8JSParser(URL baseUrl, ImpAnalyzer impa, PrintStream out) {
		super(baseUrl, impa, out);
	}

	/**
	 * @param baseUrl
	 * @param impa
	 */
	public CheckM8JSParser(URL baseUrl, ImpAnalyzer impa) {
		super(baseUrl, impa);
	}
	
	
	/*
	 * overide the getScriptContent method to do the specical script parse
	 */
	protected String getScriptContent(String sScript){
		if( null != getSrcTagValue(sScript) && getSrcTagValue(sScript).equals( CM8_SRC ) )
		{
			String CM8Server = Context.toString(m_scope.get("CM8Server", m_scope));
			String CM8Cat = Context.toString(m_scope.get("CM8Cat", m_scope));
			
			String $1 = m_sbJs.toString();
			//parse it.
			m_cx.evaluateString(m_scope, $1, "MySource", 1, null);
			
			String $2 = Context.toString(m_scope.get("url", m_scope)).trim() ;
			String $3 = super.getScriptContent(
			"<Script language=\"javascript\" src="
			+$2+
	        "></script>"
			).trim() ;

			m_cx.evaluateString(m_scope, $3, "MySource", 1, null);
			String $4 = 
			Context.toString(m_scope.get("application", m_scope)).trim() ;
			
			String $5 = 
			super.getScriptContent(
			"<Script language=\"javascript\" src="
			+$4+
	        "></script>"
			).trim() ;
			
			this.clearDocument();
			
			int $6 = $5.indexOf("function");
			int $7 = $5.indexOf("var CM8CheckErrorsAlreadyCalled");
			$5 = $5.substring($6,$7);
			
			$5 = $5 
			+ " var CM8ShowAd = function(F, I) " 
			+ " { " 
			+ " if (typeof(CM8MultiShow) != \"undefined\") " 
			+ " CM8MultiShow(F, I); " 
			+ " }"  ;
			
			return $5 ;
		}
		else
		{
			return super.getScriptContent(sScript);
		}
	}
	
	/*
	 * get src tag value
	 */
	protected String getSrcTagValue(String sScript)
	{
		int iIndex = sScript.indexOf(">");
		if(iIndex < 0){
			return "";
		}
		String sStartTag = sScript.substring(0, iIndex + 1);
		String sJudge = sStartTag.toLowerCase();
		//don't contain <script
		if(sJudge.indexOf(SCRIPT_START) < 0){
			return "";
		}
		String sSrc = null;
		try{
			TagAttributeParser tag = new TagAttributeParser(sStartTag);
			//get src
			sSrc = tag.getValue("src");
			//get language
			String sLan = tag.getValue("language");
			if(sLan != null){
				sLan = sLan.toLowerCase();
				//if isn't javascript, don't parse it.
				if(sLan.indexOf("javascript") < 0){
					return "";
				}
			}
		}catch (Exception e){
		IaaUtil.printStackTrace(e);
		IaaUtil.log("tag Like this:\n" + sStartTag);
		return "";
		}
		return sSrc ;
	}
	
	public static void main2(String args[])
	{
		demo();
	}
	
	public static final int SIZE = 30720;
    private static StringBuffer m_sbJs = new StringBuffer(SIZE);
	static{
		try{
	        //get the html object from js file.
			//and save it to the buffer than reuse it.
			BufferedReader jsFile = new BufferedReader(new FileReader("./resources/cm8adam_1_call.js"));
	        char[] buf = new char[SIZE];
			while(true){
	            int moved = jsFile.read(buf);
	            if ( moved < 0 ) break;
	            m_sbJs.append(buf, 0, moved);
			}
			jsFile.close();
	    }catch (Exception e) {
	    	IaaUtil.printStackTrace(e);
	    }
	}
	public static void demo2()
	{
		try{
			URL url = URLUtil.getURL("http://www.sohu.com");
			CheckM8JSParser parser = new CheckM8JSParser(url, new ImpAnalyzerImpl());
			if(parser.IsIniSuccessful()){
			    try{
					
					String sScript = m_sbJs.toString();
					//parse it.
					parser.m_cx.evaluateString(parser.m_scope, sScript, "MySource", 1, null);
					
					//System.out.println( Context.toString(parser.m_scope.get("url", parser.m_scope)));
					
			    }catch (JavaScriptException jse) {
			    	jse.printStackTrace();
			    }catch (Exception e) {
			    	IaaUtil.printStackTrace(e);
			    	e.printStackTrace();
			    }
			}
		}catch(MalformedURLException e){
			e.printStackTrace();
			return;
		}
	}
		
	public static void demo()
	{
		try{
			URL url = URLUtil.getURL("http://www.sohu.com");
			CheckM8JSParser parser = new CheckM8JSParser(url, new ImpAnalyzerImpl());
			if(parser.IsIniSuccessful()){
				String $1 =" <Script language=\"JavaScript\"> " +
				" var CM8Server = \"web.checkm8.com\"; " +
				" var CM8Cat = \"vnu_mma_aw.Homepage\"; " +
				" </script> " ;
				String $2 = " <Script language=\"JavaScript\" src=\"http://web.checkM8.com/adam/cm8adam_1_call.js\"></script> " ;
				String $3 = " <Script language=\"JavaScript\"> " +
							" CM8ShowAd(\"Top\"); " +
							" document.write('<br>'); " +
							" CM8ShowAd(\"Left\"); " +
							" document.write('<br>'); " +
							" CM8ShowAd(\"Sponsorship_Right\"); " +
							" document.write('<br>'); " +
							" CM8ShowAd(\"Right\"); " +
							" document.write('<br>'); " +
							" CM8ShowAd(\"Anchor\");"+
							//" document.write('<br>'); " +
							//" CM8ShowAd(\"BB_Sponsor_3\");"+
                            " </script>" ;
			
				
				if(parser.ParseScriptTag($1) &&  parser.ParseScriptTag($2) && parser.ParseScriptTag($3)){
					System.out.println(parser.getDocument());
					HashMap map = parser.getPopup();
					if(map != null){
						List lst = (List)map.get(MAP_POPUP_URL);
						for(int i = 0; i < lst.size(); i++){
							System.out.println(lst.get(i).toString());
						}
						lst = (List)map.get(MAP_POPUP_CONTENT);
						for(int i = 0; i < lst.size(); i++){
							System.out.println(lst.get(i).toString());
						}
					}
				}
			}
		}catch(MalformedURLException e){
			e.printStackTrace();
			return;
		}
	}
	
	public static void main(String args[])
	{
	    String CM8Server = null ;
	    String CM8Cat = null ;
	    LinkedList params = new LinkedList();
	    
	    if( args.length <= 3)
	    {
	        System.out.println("");
	    }
	    
	    for (int i = 0; i < args.length; i++)
		{
			if (args[i].startsWith("-CM8Server:"))
			    CM8Server = args[i].substring(11);
			else if (args[i].startsWith("-CM8Cat:"))
			    CM8Cat = args[i].substring(8);
			else if (args[i].startsWith("-P:"))
			    params.add(args[i].substring(3));
		}
	    if( CM8Server == null || CM8Cat == null || params.size() == 0 )
	    {
	        System.out.println("Usage: CheckM8JSParser -CM8Server:<CM8Server> -CM8Cat:<CM8Cat> -P:ad1 -P:ad2 -P:ad3");
			return;
	    }
	    try{
		    URL url = URLUtil.getURL("http://localhost/");
			CheckM8JSParser parser = new CheckM8JSParser(url, new ImpAnalyzerImpl());
			if(parser.IsIniSuccessful()){
				String $1 =" <Script language=\"JavaScript\"> " +
				" var CM8Server = \""+CM8Server+"\"; " +
				" var CM8Cat = \""+CM8Cat+"\"; " +
				" </script> " ;
				String $2 = " <Script language=\"JavaScript\" src=\"http://web.checkM8.com/adam/cm8adam_1_call.js\"></script> " ;
				String $3_0 = " <Script language=\"JavaScript\"> " ;
							/*" CM8ShowAd(\"Top\"); " +
							" document.write('<br>'); " +
							" CM8ShowAd(\"Left\"); " +
							" document.write('<br>'); " +
							" CM8ShowAd(\"Sponsorship_Right\"); " +
							" document.write('<br>'); " +
							" CM8ShowAd(\"Right\"); " +
							" document.write('<br>'); " +
							" CM8ShowAd(\"Anchor\");"+
							//" document.write('<br>'); " +
							//" CM8ShowAd(\"BB_Sponsor_3\");"+
	                        " </script>" ;*/
				String $3_1 = "";
				for(Iterator it = params.iterator(); it.hasNext() ;)
				{
				    $3_1+=" CM8ShowAd(\"" + it.next() + "\"); document.write(\"<br>\");";
				}
				String $3_2 =  " </script>" ;
				String $3 = $3_0 + $3_1 + $3_2 ;
				
				if(parser.ParseScriptTag($1) &&  parser.ParseScriptTag($2) && parser.ParseScriptTag($3)){
				    System.out.println("<html><head></head><body>");
					System.out.println(parser.getDocument());
				    System.out.println("</body></html>");
				    /*
					HashMap map = parser.getPopup();
					if(map != null){
						List lst = (List)map.get(MAP_POPUP_URL);
						for(int i = 0; i < lst.size(); i++){
							System.out.println(lst.get(i).toString());
						}
						lst = (List)map.get(MAP_POPUP_CONTENT);
						for(int i = 0; i < lst.size(); i++){
							System.out.println(lst.get(i).toString());
						}
					}*/
				}
			}
		}catch(MalformedURLException e){
			e.printStackTrace();
			return;
		}
	    
	}
}
